﻿Imports NVelocity
Imports NVelocity.App
Imports NVelocity.Context

Imports System.Collections.Generic
Imports System.IO
Imports System.Globalization

Partial Class WebForm_QueryVBook
    Inherits MyUserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
        
            RaiseEvent Loaded(Me, New EventArgs)


            Dim d As New DateTime(1979, 5, 11)



        End If
        '志工隊不能印志工證和名條
        If Me.CanEdit = False Then
            btnPrintVCard.Visible = False
            btnPrintVBook.Visible = False
        Else
            btnPrintVCard.Visible = True
            btnPrintVBook.Visible = True
        End If
        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(Me.btnExcel)
        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(Me.btnExcel2)
        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(Me.btnPrintVCard)
        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(Me.btnPrintVBook)
    End Sub

    Protected Sub gv_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
        Dim row As GridViewRow = Me.gv.FindRow(e.CommandSource)
        If e.CommandName = "MyView" Then
            Me.CurrentRowIndex = row.RowIndex
            RaiseEvent Viewing(Me, EventArgs.Empty)
        ElseIf e.CommandName = "Reject" Then
            Dim Active As String = Me.gv.DataKeys(row.RowIndex)("VBookActive")
            Dim VolunteerID As String = Me.gv.DataKeys(row.RowIndex)("VolunteerID")
            Dim ID As String = Me.gv.DataKeys(row.RowIndex)("ID")
            If Active = "Y" And GetVBookData(VolunteerID, "N") = True Then
                UpdateVBookActive(VolunteerID, ID)

            Else
                DeleteVbookData(ID)
            End If

            Me.BindGV()
            MyObj.ShowMessage("收回成功!")
        End If
    End Sub
    Private Sub UpdateVBookActive(ByVal VolunteerID As String, ByVal ID As String)
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        sql.Length = 0
        sql.AppendFormat("Update Vbook Set ")
        sql.AppendFormat("Active='Y' ")
        sql.AppendFormat(",UpdateDate=getdate() ")
        sql.AppendFormat(",UpdateBy='{0}' ", clsAuth.GetUserID())
        sql.AppendFormat("where ID in (Select top 1 ID from Vbook where Active='N' and VolunteerID='{0}' order by IssueDate desc); ", VolunteerID)
        sql.AppendFormat("Delete from Vbook ")
        sql.AppendFormat("where ID='{0}'; ", ID)
        dat.AccData(sql)

    End Sub
    Private Sub DeleteVbookData(ByVal ID As String)
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        sql.Length = 0
        sql.AppendFormat("Delete from Vbook ")
        sql.AppendFormat("where ID='{0}' ", ID)

        dat.AccData(sql)
    End Sub
    Private Function GetVBookData(ByVal VolunteerID As String, ByVal Active As String) As Boolean
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.Length = 0
        sql.AppendFormat("Select * from VBook ")
        sql.AppendFormat("where VolunteerID='{0}' ", VolunteerID)
        sql.AppendFormat("and Active='{0}' ", Active)

        If dat.GetData(sql).Rows.Count > 0 Then
            Return True
        Else
            Return False
        End If

    End Function
    Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
        Dim row As MyGridViewRow = TryCast(e.Row, MyGridViewRow)

        If e.Row.RowType = DataControlRowType.DataRow Then
            If row.Eval("VBookActive") = "Y" Then
                row.FindMVControl("mvDetailViewMode").SetActiveView(row.FindvwControl("vwEdit"))
            Else

                row.FindMVControl("mvDetailViewMode").SetActiveView(row.FindvwControl("vwView"))
            End If

        End If
    End Sub


    Protected Sub gv_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gv.SelectedIndexChanged
        Me.CurrentRowIndex = Me.gv.SelectedIndex
        RaiseEvent SelectedIndexChanged(Me, New EventArgs)
    End Sub

    Protected Sub gv_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gv.PageIndexChanging
        Me.gv.PageIndex = e.NewPageIndex
        Me.BindGV()
    End Sub

    Protected Sub btnQuery_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnQuery.Click
        '重印功能無效
        'Me.chkPrintVCard.Checked = False
        RaiseEvent btnQueryClick(Me, New EventArgs)
    End Sub

    Protected Sub btnExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExcel.Click
        '重印功能無效
        'Me.chkPrintVCard.Checked = True

        Me.Export()
    End Sub

    Protected Sub btnExcel2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExcel2.Click
        '重印功能無效
        'Me.chkPrintVCard.Checked = True

        Me.Export2()
    End Sub

    Protected Sub btnPrintVCard_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrintVCard.Click
        Me.PrintVCard()
    End Sub

    Protected Sub gv_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gv.Sorting
        Me.BindGV()
    End Sub

    Protected Sub btnPrintVBook_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrintVBook.Click
        Me.PrintVolunteerBook(True)
    End Sub
End Class

Partial Class WebForm_QueryVBook

    Public Sub BindGV()
        Me.BindGV(Me.gv)
    End Sub

    Private Sub BindGV(ByVal gv As GridView)

        'gv.p
        Me.gv.Columns(6).Visible = IsVisible
        Me.gv.Columns(7).Visible = IsVisible
        gv.DataSource = Me.BindGVData()
        gv.DataBind()
    End Sub

    Private Function BindGVData() As Data.DataTable
        Return Me.BindGVData("", True)
    End Function

    Private Function BindGVData(ByVal tempTable As String, ByVal rePrint As Boolean) As Data.DataTable
        Dim dat As New clsData
        Dim sql As MyStringBuilder
        Dim dt As Data.DataTable

        If tempTable = "" Then
            sql = New MyStringBuilder
        Else
            sql = New MyStringBuilder
        End If

        sql.AppendFormat(" select v.VolunteerID,v.PhotoPath,v.VolunteerName, vb.Status, vb.ID, VBookActive = vb.Active  ")
        sql.AppendFormat(",vb.VBookID ")
        sql.AppendFormat(",2 as VBookTypeID, '050' as SerialGroupID, vb.SerialNumber, vb.IssueDate, vb.CountyID ,vb.Comment ")
  
        sql.AppendFormat(",oo.VOrganizationName ")

        sql.AppendFormat(",ov.OrganizationName ")
        If tempTable <> "" Then
            sql.AppendFormat("into {0} ", tempTable)
        End If

        sql.AppendFormat(" from VolunteerDistinctView v ")
        sql.AppendFormat(" inner join VBookView vb on v.VolunteerID = vb.VolunteerID ")

        sql.AppendFormat("  left JOIN (select vm.VOrganizationID,vo.VOrganizationName,vm.VolunteerID ,vo.DirectUOrganizationID from VOrganizationMapping vm ")
        sql.AppendFormat("inner join VOrganizationViewV2 vo on vm.VOrganizationID=vo.VOrganizationID ) oo on v.VolunteerID=oo.VolunteerID  ")
        sql.AppendFormat("left join OrganizationView ov on oo.DirectUOrganizationID=ov.UOrganizationID ")

        sql.AppendFormat(" where v.Active = '{0}' ", My.VolunteerStatus.VBooked.ToString())
        If tempTable <> "" Then
            sql.AppendFormat("and vb.Active='Y' ")
        End If
        sql.AppendFormat(GetWhereSQL(reprint))

        sql.AppendFormat(Me.gv.OrderBySQL & " ")

        If tempTable <> "" Then
            sql.AppendFormat("select * from {0} ", tempTable)
        End If
        '  MyObj.WriteErrorLog(sql.ToString)

        Return dat.GetData(sql)
    End Function

    Private Function BindGV2() As Data.DataTable
        Dim dat As New clsData
        Dim sql As New MyStringBuilder


        sql.AppendFormat(" select v.* ")
        sql.AppendFormat(",Case v.Gender when 'F' then '女' else '男' end vGender ")
        'sql.AppendFormat(GetDate("v.Birthday", "vBirthday"))
        sql.AppendFormat(", vBirthday = v.Birthday ")
        sql.AppendFormat(",vb.VBookID,R1.RegionName")
        sql.AppendFormat(",2 as VBookTypeID, '050' as SerialGroupID, vb.SerialNumber, vb.IssueDate ")
        sql.AppendFormat(",'' as Picture,'V' as GetVBook,'' as ChangeVBook ")
        'sql.AppendFormat(GetDate("tgb.StartDate", "tgbStartDate"))
        sql.AppendFormat(", tgbStartDate = tgb.StartDate ")
        sql.AppendFormat(", o_tgb.OrganizationName as trbOrg, o_tgs.OrganizationName as trsOrg ")
        'sql.AppendFormat(GetDate("tgs.StartDate", "tgsStartDate"))
        sql.AppendFormat(", tgsStartDate = tgs.StartDate ")
        sql.AppendFormat(", r1.RegionID ")
        sql.AppendFormat(",oo.VOrganizationName ")
        sql.AppendFormat(",oo.DirectUOrganizationID ")
        sql.AppendFormat(",oo.VOrganizationID ")
        sql.AppendFormat(",oo.OrganizationName ")
        sql.AppendFormat(" from Volunteer v ")
        sql.AppendFormat(" inner join VBookView vb on v.VolunteerID = vb.VolunteerID ")
        sql.AppendFormat(" Left join Village R1 on v.VillageID = R1.RegionID ")
        sql.AppendFormat(" inner join trainingregister trb on v.VolunteerID = trb.VolunteerID and trb.CheckStatus = '3' ")
        sql.AppendFormat(" inner join trainingcoursegroup tgb on trb.GroupID = tgb.ID and tgb.GroupType='B' ")
        sql.AppendFormat(" inner join trainingregister trs on v.VolunteerID = trs.VolunteerID and trs.CheckStatus = '3' ")
        sql.AppendFormat(" inner join trainingcoursegroup tgs on trs.GroupID = tgs.ID and tgs.GroupType='S' ")
        sql.AppendFormat(" inner join OrganizationView o_tgb on tgb.UOrganizationID = o_tgb.UOrganizationID ")
        sql.AppendFormat(" inner join OrganizationView o_tgs on tgs.UOrganizationID = o_tgs.UOrganizationID ")
        sql.AppendFormat("  left JOIN (select vm.VOrganizationID,vo.VOrganizationName,vm.VolunteerID ,vo.DirectUOrganizationID,vo.OrganizationName from VOrganizationMapping vm ")
        sql.AppendFormat("inner join VOrganizationView vo on vm.VOrganizationID=vo.VOrganizationID ) oo on v.VolunteerID=oo.VolunteerID  ")
        sql.AppendFormat(" where v.Active = '{0}' ", My.VolunteerStatus.VBooked.ToString())
        sql.AppendFormat(GetWhereSQL(Me.chkPrintVCard.Checked))

        sql.AppendFormat(" order by r1.TownName, r1.RegionName, v.VolunteerName ")
        'MyObj.WriteErrorLog(sql.ToString())

        Return dat.GetData(sql)
    End Function

    Private Function BindGV3() As Data.DataTable
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

 

        sql.AppendFormat(" select v.* ")
        sql.AppendFormat(",Case v.Gender when 'F' then '女' else '男' end vGender ")
        sql.AppendFormat(", vBirthday = v.Birthday ")
        sql.AppendFormat(",R1.RegionName")
        sql.AppendFormat(",2 as VBookTypeID, '050' as SerialGroupID")
        sql.AppendFormat(",'' as Picture ")
        sql.AppendFormat(" , case when vb.Status='2' then 'V' else '' end as GetVBook ")
        sql.AppendFormat(" , case when vb.Status='4' then 'V' else '' end as ChangeVBook ")
        sql.AppendFormat(", tgbStartDate = tgb.StartDate ")
        sql.AppendFormat(", o_tgb.OrganizationName as trbOrg, o_tgs.OrganizationName as trsOrg ")
        sql.AppendFormat(", tgsStartDate = tgs.StartDate ")
        sql.AppendFormat(", vb.VBookID ")
        sql.AppendFormat(", r1.RegionID ")
        sql.AppendFormat(",oo.VOrganizationID ")

        sql.AppendFormat(",oo.VOrganizationName ")
        sql.AppendFormat(",oo.DirectUOrganizationID ")
        sql.AppendFormat(",org.OrganizationName ")
        sql.AppendFormat(" from Volunteer v ")
        sql.AppendFormat(" inner join VBookView vb on v.VolunteerID = vb.VolunteerID ")
        sql.AppendFormat(" Left join Village R1 on v.VillageID = R1.RegionID ")

        '最近一筆基礎訓上課紀錄
        sql.AppendFormat(" left join ( select VolunteerID, GroupID = max(GroupID) from TrainingRegister trb ")
        sql.AppendFormat("          inner join trainingcoursegroup tgb on trb.GroupID = tgb.ID and tgb.GroupType='B' where trb.CheckStatus = '3' group by VolunteerID ")
        sql.AppendFormat("  ) tgb2 on v.VolunteerID = tgb2.VolunteerID ")

        sql.AppendFormat(" left join TrainingCourseGroup tgb on tgb.ID = tgb2.GroupID ")

        '最近一筆特殊訓上課紀錄
        sql.AppendFormat(" left join ( select VolunteerID, GroupID = max(GroupID) from TrainingRegister trs ")
        sql.AppendFormat("          inner join trainingcoursegroup tgs on trs.GroupID = tgs.ID and tgs.GroupType='S' where trs.CheckStatus = '3' group by VolunteerID ")
        sql.AppendFormat("  ) tgs2 on v.VolunteerID = tgs2.VolunteerID ")

        sql.AppendFormat(" left join TrainingCourseGroup tgs on tgs.ID = tgs2.GroupID ")

        'sql.AppendFormat(" left join (select tgs.StartDate, trs.VolunteerID from trainingregister trs ")
        'sql.AppendFormat(" inner join trainingcoursegroup tgs on trs.GroupID = tgs.ID and tgs.GroupType='S' ")
        'sql.AppendFormat(" where trs.CheckStatus = '3') tgs on v.VolunteerID = tgs.VolunteerID ")
        sql.AppendFormat(" left join OrganizationView o_tgb on tgb.UOrganizationID = o_tgb.UOrganizationID ")
        sql.AppendFormat(" left join OrganizationView o_tgs on tgs.UOrganizationID = o_tgs.UOrganizationID ")
        sql.AppendFormat("  left JOIN (select vm.VOrganizationID,vo.VOrganizationName,vm.VolunteerID,vo.DirectUOrganizationID from VOrganizationMapping vm ")
        sql.AppendFormat("inner join VOrganizationViewV2 vo on vm.VOrganizationID=vo.VOrganizationID ) oo on v.VolunteerID=oo.VolunteerID  ")
        sql.AppendFormat("left join  OrganizationView org on oo.DirectUOrganizationID=org.UOrganizationID ")
        sql.AppendFormat(" where 1=1 ")
        sql.AppendFormat("and v.Active = '{0}' ", My.VolunteerStatus.VBooked.ToString())
        sql.AppendFormat(GetWhereSQL(Me.chkPrintVCard.Checked))

        sql.AppendFormat(" order by org.OrganizationName,oo.VOrganizationName,vb.VBookID ")
        'MyObj.WriteLog(sql.ToString())

        Return dat.GetData(sql)
    End Function

    Private Sub Export()
   

        Dim dt As New System.Data.DataTable

        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.Length = 0

       


        sql.AppendFormat(" select case when vb.StatePaperID='' then '' else vb.StatePaperID+'號' end as StatePaperID ,vb.VBookID,vb.IssueDate,R1.TownName+R1.RegionName as VillageName ")
        sql.AppendFormat(" ,org.OrganizationName,oo.VOrganizationName,v.VolunteerName ")
        sql.AppendFormat(" ,Case v.Gender when 'F' then '女' else '男' end Gender ")
        sql.AppendFormat(" ,v.IdentificationID , v.Birthday ")
        sql.AppendFormat(" , tgbStartDate = tgb.StartDate ")
        sql.AppendFormat(" , o_tgb.OrganizationName as tgbOrgName ")
        sql.AppendFormat(" , tgsStartDate = tgs.StartDate , o_tgs.OrganizationName as tgsOrgName ")
        sql.AppendFormat(" , v.Address,v.OfficePhone, case when vb.Status='2' then 'V' else '' end as GetVBook ")
        sql.AppendFormat(" , case when vb.Status='4' then 'V' else '' end as ChangeVBook,vb.Comment ")
        sql.AppendFormat(" from Volunteer v ")
        sql.AppendFormat(" inner join VBookView vb on v.VolunteerID = vb.VolunteerID ")
        sql.AppendFormat(" Left join Village R1 on v.VillageID = R1.RegionID ")

        '所屬志工隊
        sql.AppendFormat("left JOIN (select distinct vo.VOrganizationName,vo.DirectUOrganizationID,vm.VolunteerID from VOrganizationMapping vm ")
        sql.AppendFormat("inner join VOrganizationViewV2 vo on vm.VOrganizationID=vo.VOrganizationID ) oo on v.VolunteerID=oo.VolunteerID ")
        sql.AppendFormat("left join  OrganizationView org on oo.DirectUOrganizationID=org.UOrganizationID ")


        '最近一筆基礎訓上課紀錄
        sql.AppendFormat(" left join ( select VolunteerID, GroupID = max(GroupID) from TrainingRegister trb ")
        sql.AppendFormat(" inner join trainingcoursegroup tgb on trb.GroupID = tgb.ID and tgb.GroupType='B' where trb.CheckStatus = '3' group by VolunteerID ")
        sql.AppendFormat(" ) tgb2 on v.VolunteerID = tgb2.VolunteerID ")        '
        sql.AppendFormat(" left join TrainingCourseGroup tgb on tgb.ID = tgb2.GroupID ")

        '最近一筆特殊訓上課紀錄
        sql.AppendFormat(" left join ( select VolunteerID, GroupID = max(GroupID) from TrainingRegister trs ")
        sql.AppendFormat(" inner join trainingcoursegroup tgs on trs.GroupID = tgs.ID and tgs.GroupType='S' where trs.CheckStatus = '3' group by VolunteerID ")
        sql.AppendFormat(" ) tgs2 on v.VolunteerID = tgs2.VolunteerID ")
        sql.AppendFormat(" left join TrainingCourseGroup tgs on tgs.ID = tgs2.GroupID ")


        sql.AppendFormat(" left join OrganizationView o_tgb on tgb.UOrganizationID = o_tgb.UOrganizationID ")
        sql.AppendFormat(" left join OrganizationView o_tgs on tgs.UOrganizationID = o_tgs.UOrganizationID ")
        sql.AppendFormat(" where 1=1 ")
        sql.AppendFormat(" and v.Active = 'Y' ")
        sql.AppendFormat(" and vb.IssueDate Between '{0:yyyy/MM/dd}' ", Me.txtIssueStartDate.Value)
        sql.AppendFormat(" and '{0:yyyy/MM/dd}' ", Me.txtIssueEndDate.Value)
        sql.AppendFormat("order by v.VolunteerName,org.OrganizationName,oo.VOrganizationName ")


        dt = dat.GetData(sql)
        If dt.Rows.Count > 0 Then

            For i As Integer = 0 To dt.Columns.Count - 1
                Select Case i
                    Case 0
                        dt.Columns(0).ColumnName = "發 文 字 號"
                    Case 1
                        dt.Columns(1).ColumnName = "紀 錄 冊 證 號"
                    Case 2
                        dt.Columns(2).ColumnName = "紀錄冊核發日期"
                    Case 3
                        dt.Columns(3).ColumnName = "區 與 里 "
                    Case 4
                        dt.Columns(4).ColumnName = "運 用 單 位"
                    Case 5
                        dt.Columns(5).ColumnName = "志 工 隊"
                    Case 6
                        dt.Columns(6).ColumnName = "姓 名"
                    Case 7
                        dt.Columns(7).ColumnName = "性別"
                    Case 8
                        dt.Columns(8).ColumnName = "身份證或護照"
                    Case 9
                        dt.Columns(9).ColumnName = "出生年月日"
                    Case 10
                        dt.Columns(10).ColumnName = "基礎訓練"
                    Case 11
                        dt.Columns(11).ColumnName = "訓練單位(基礎)"
                    Case 12
                        dt.Columns(12).ColumnName = "特殊訓練"
                    Case 13
                        dt.Columns(13).ColumnName = "訓練單位(特殊)"
                    Case 14
                        dt.Columns(14).ColumnName = "地            址"
                    Case 15
                        dt.Columns(15).ColumnName = "電  話"
                    Case 16
                        dt.Columns(16).ColumnName = "領冊"
                    Case 17
                        dt.Columns(17).ColumnName = "補發"
                    Case 18
                        dt.Columns(18).ColumnName = "備  註"



                End Select
            Next
            dt.Columns.Add("發冊數")
            dt.Columns(19).SetOrdinal(1)

         
            For i As Integer = 0 To dt.Rows.Count - 1
                dt.Rows(i)("發冊數") = i + 1

                '    dt.Rows(i)("運用單位") = Me.GetVOrganization(dt.Rows(i)("身份證或護照").ToString(), "OrganizationName")
                '   dt.Rows(i)("志工隊") = Me.GetVOrganization(dt.Rows(i)("身份證或護照").ToString(), "VOrganizationName")
            Next
            Dim ms As MemoryStream = TryCast(DataTableRenderToExcel.RenderDataTableToExcelSetSheet(dt, "志工名冊總表"), MemoryStream)

            ' 設定強制下載標頭。 
            Response.AddHeader("Content-Disposition", String.Format("attachment; filename=VBook.xls"))
            ' 輸出檔案。 
            Response.BinaryWrite(ms.ToArray())

            ms.Close()
            ms.Dispose()
        Else
            MyObj.ShowMessage("您選擇的資料類型沒有資料可供匯出!")
        End If
        'For i As Integer = 0 To dt.Rows.Count - 1
        '    v = New VBookList

        '    If Convert.ToString(dt.Rows(i)("StatePaperID")) = "" Then
        '        v.StatePaperID = dt.Rows(i)("StatePaperID").ToString()
        '    Else
        '        v.StatePaperID = dt.Rows(i)("StatePaperID").ToString() + "號"
        '    End If

        '    v.NO = i + 1
        '    v.SerialNumber = dt.Rows(i)("VBookID").ToString()
        '    v.IssueDate = dt.Rows(i)("IssueDate").ToString()
        '    v.VillageName = dt.Rows(i)("VillageName").ToString()
        '    v.VOrgName = dt.Rows(i)("VOrgName").ToString()
        '    v.VolunteerName = dt.Rows(i)("VolunteerName").ToString()
        '    v.Gender = dt.Rows(i)("Gender").ToString()
        '    v.IdentificationID = dt.Rows(i)("IdentificationID").ToString()
        '    v.Birthday = dt.Rows(i)("Birthday").ToString()
        '    v.tgbStartDate = dt.Rows(i)("tgbStartDate").ToString()
        '    v.tgbOrgName = dt.Rows(i)("tgbOrgName").ToString()
        '    v.tgsStartDate = dt.Rows(i)("tgsStartDate").ToString()
        '    v.tgsOrgName = dt.Rows(i)("tgsOrgName").ToString()
        '    v.Address = dt.Rows(i)("Address").ToString()
        '    v.OfficePhone = dt.Rows(i)("OfficePhone").ToString()

        '    '判斷是否為補發 '2'為首發，'4'為補發
        '    If Convert.ToString(dt.Rows(i)("Active")) = "4" Then
        '        v.Active1 = ""
        '        v.Active2 = "V"
        '    ElseIf Convert.ToString(dt.Rows(i)("Active")) = "2" Then
        '        v.Active1 = "V"
        '        v.Active2 = ""
        '    End If

        '    v.Comment = dt.Rows(i)("Comment").ToString()

        '    vcList.Add(v)

        'Next

        'Dim fileName As String = "VBook.xls"
        'Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName)
        'Response.ContentType = "application/vnd.ms-excel"

        'Dim velocity As New VelocityEngine
        'Dim props As New Commons.Collections.ExtendedProperties

        ''fix bug
        'props.AddProperty("file.resource.loader.path", Server.MapPath("~\App_Data"))
        'props.AddProperty("input.encoding", "utf-8")
        'props.AddProperty("output.encoding", "utf-8")
        'velocity.Init(props)

        'Dim template As Template

        'Dim context As New VelocityContext
        'template = velocity.GetTemplate("志工名冊總表.xml")

        ''Dim approveDate As Date = Date.Now
        ''context.Put("ApproveDate", approveDate.Date.ToString("yyyy年MM月dd日"))
        ''context.Put("ApproveDateLabel", "核發日期:")
        'context.Put("RowCount", dt.Rows.Count + 4)
        'context.Put("vcList", vcList)
        'context.Put("User", clsAuth.GetUserID())
        'context.Put("DownloadDate", Today.Year.ToString() & "-" & Today.Month.ToString() & "-" & Today.Day.ToString() & "T" & Now.Hour.ToString() & ":" & Now.Minute.ToString() & ":" & Now.Second.ToString() & "Z")
        'context.Put("IP", MyObj.getIP())
        'Dim writer As New IO.StringWriter
        'template.Merge(context, writer)

        'Response.Write(writer.GetStringBuilder().ToString())

        'Response.End()

    End Sub

    Private Sub Export2()
        Dim vcList As New List(Of VBook)
        Dim v As VBook
        Dim dt As System.Data.DataTable

        Dim i As Integer = 0
        Dim prevRegionID As String
        Dim base As Integer = 4
        Dim RowCount As Integer = 1
        'Dim CmpString As String = ""

        dt = Me.BindGV3()
        For Each dr As Data.DataRow In dt.Rows
            If prevRegionID <> "" AndAlso prevRegionID <> dr("VOrganizationName") Then

                If i Mod base <> 0 Then
                    For j As Integer = i Mod base To base - 1
                        v = New VBook
                        vcList.Add(v)

                        i = i + 1
                    Next
                End If
                RowCount = (base - (RowCount Mod 4)) + 1 + RowCount
                i = 0
            End If
            'If Not CmpString.Contains(dr("VolunteerID").ToString) Then

            v = New VBook
            v.SerialNumber = dr("VBookID").ToString().Substring(0, dr("VBookID").ToString().Length - 1)

            If Not TypeOf dr("PhotoPath") Is DBNull Then
                v.Picture = Me.GetPhoto(dr("PhotoPath").ToString())
            Else
                v.Picture = ""
            End If

            If Not TypeOf dr("OrganizationName") Is DBNull AndAlso RowCount Mod base = 1 Then
                v.OrganizationName = dr("OrganizationName").ToString() & Space(1) & dr("VOrganizationName").ToString()
            Else
                v.OrganizationName = ""
            End If

            If v.OrganizationName.Length > 9 Then
                v.VSpace = Space(51 - (v.OrganizationName.Length - 10) * 2)
            Else
                v.OrganizationName = Space(16)
                v.VSpace = Space(51)
            End If
            v.RegionName = dr("RegionName").ToString
            v.VolunteerName = dr("VolunteerName").ToString
            v.vGender = dr("vGender").ToString
            v.VolunteerID = dr("VolunteerID").ToString
            ' CmpVolunteerID &= dr("VolunteerID").ToString & ","
            v.vBirthday = dr("vBirthday").ToString()
            'MyObj.WriteLog(v.vBirthday)
            v.tgbStartDate = dr("tgbStartDate").ToString
            v.trbOrg = dr("trbOrg").ToString
            v.tgsStartDate = dr("tgsStartDate").ToString
            v.trsOrg = dr("trsOrg").ToString
            v.Address = dr("Address").ToString
            v.OfficePhone = dr("OfficePhone").ToString
            v.GetVBook = dr("GetVBook").ToString
            v.ChangeVBook = dr("ChangeVBook").ToString
            ' v.Index = i
            v.Index = RowCount + 2
            vcList.Add(v)

            i = i + 1
            RowCount = RowCount + 1

            If Not TypeOf (dr("VOrganizationName")) Is DBNull Then
                prevRegionID = dr("VOrganizationName")
            Else
                prevRegionID = ""
            End If
            '  End If
        Next

        'Print

        Dim fileName As String = "VBook.doc"
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName)
        Response.ContentType = "application/msword"

        Dim velocity As New VelocityEngine
        Dim props As New Commons.Collections.ExtendedProperties

        'fix bug
        props.AddProperty("file.resource.loader.path", Server.MapPath("~\App_Data"))
        props.AddProperty("input.encoding", "utf-8")
        props.AddProperty("output.encoding", "utf-8")
        velocity.Init(props)

        Dim template As Template

        Dim context As New VelocityContext
        'template = velocity.GetTemplate("紀錄冊核發名冊範例.xml")
        template = velocity.GetTemplate("臺北縣環境保護志願服務紀錄冊核發名冊 v01.xml")
        context.Put("User", clsAuth.GetUserID())
        context.Put("DownloadDate", Today.Year.ToString() & "-" & Today.Month.ToString() & "-" & Today.Day.ToString() & "T" & Now.Hour.ToString() & ":" & Now.Minute.ToString() & ":" & Now.Second.ToString() & "Z")
        context.Put("IP", MyObj.getIP())
        'context.Put("OrganizationName", Me.VolunteerQueryControl1.VOrganizationName)

        context.Put("Title", "新北市環境保護志願服務紀錄冊核發名冊")

        Dim approveDate As Date = Date.Now
        context.Put("ApproveDate", approveDate.Date.ToString("yyyy年MM月dd日"))
        context.Put("ApproveDateLabel", "核發日期:")
        context.Put("VBook", vcList)

        Dim writer As New IO.StringWriter
        template.Merge(context, writer)

        Response.Write(writer.GetStringBuilder().ToString())

        Response.End()


    End Sub
    Public Class VBook
        Private OrganizationNameField As String = ""
        Private SerialNumberField As String = ""
        Private PictureField As String = ""
        Private RegionNameField As String = ""
        Private VolunteerNameField As String = ""
        Private vGenderField As String = ""
        Private VolunteerIDField As String = ""
        Private vBirthdayField As String = ""
        Private tgbStartDateField As String = ""
        Private trbOrgField As String = ""
        Private tgsStartDateField As String = ""
        Private trsOrgField As String = ""
        Private AddressField As String = ""
        Private OfficePhoneField As String = ""
        Private GetVBookField As String = ""
        Private ChangeVBookField As String = ""
        Private VSpaceField As String = ""
        Private IndexField As Integer
        Public Property VSpace() As String
            Get
                Return Me.VSpaceField
            End Get
            Set(ByVal value As String)
                Me.VSpaceField = value
            End Set
        End Property
        Public Property OrganizationName() As String
            Get
                Return Me.OrganizationNameField
            End Get
            Set(ByVal value As String)
                Me.OrganizationNameField = value
            End Set
        End Property

        Public Property Index() As Integer
            Get
                Return Me.IndexField
            End Get
            Set(ByVal value As Integer)
                Me.IndexField = value
            End Set
        End Property
        Public Property SerialNumber() As String
            Get
                Return Me.SerialNumberField
            End Get
            Set(ByVal value As String)
                Me.SerialNumberField = value
            End Set
        End Property
        Public Property Picture() As String
            Get
                Return Me.PictureField
            End Get
            Set(ByVal value As String)
                Me.PictureField = value
            End Set
        End Property
        Public Property RegionName() As String
            Get
                Return Me.RegionNameField
            End Get
            Set(ByVal value As String)
                Me.RegionNameField = value
            End Set
        End Property
        Public Property VolunteerName() As String
            Get
                Return Me.VolunteerNameField
            End Get
            Set(ByVal value As String)
                Me.VolunteerNameField = value
            End Set
        End Property
        Public Property vGender() As String
            Get
                Return Me.vGenderField
            End Get
            Set(ByVal value As String)
                Me.vGenderField = value
            End Set
        End Property
        Public Property VolunteerID() As String
            Get
                Return Me.VolunteerIDField
            End Get
            Set(ByVal value As String)
                Me.VolunteerIDField = value
            End Set

        End Property
        Public Property vBirthday() As String
            Get
                Return Me.vBirthdayField
            End Get
            Set(ByVal value As String)
                Me.vBirthdayField = value
            End Set
        End Property
        Public Property tgbStartDate() As String
            Get
                Return Me.tgbStartDateField
            End Get
            Set(ByVal value As String)
                Me.tgbStartDateField = value
            End Set
        End Property
        Public Property trbOrg() As String
            Get
                Return Me.trbOrgField
            End Get
            Set(ByVal value As String)
                Me.trbOrgField = value
            End Set
        End Property
        Public Property tgsStartDate() As String
            Get
                Return Me.tgsStartDateField
            End Get
            Set(ByVal value As String)
                Me.tgsStartDateField = value
            End Set
        End Property
        Public Property trsOrg() As String
            Get
                Return Me.trsOrgField
            End Get
            Set(ByVal value As String)
                Me.trsOrgField = value
            End Set

        End Property
        Public Property Address() As String
            Get
                Return Me.AddressField
            End Get
            Set(ByVal value As String)
                Me.AddressField = value
            End Set
        End Property
        Public Property OfficePhone() As String
            Get
                Return Me.OfficePhoneField
            End Get
            Set(ByVal value As String)
                Me.OfficePhoneField = value
            End Set
        End Property
        Public Property GetVBook() As String
            Get
                Return Me.GetVBookField
            End Get
            Set(ByVal value As String)
                Me.GetVBookField = value
            End Set
        End Property
        Public Property ChangeVBook() As String
            Get
                Return Me.ChangeVBookField
            End Get
            Set(ByVal value As String)
                Me.ChangeVBookField = value
            End Set
        End Property

    End Class

    Public Class VBookList

        Private StatePaperIDField As String = ""
        Private NOField As String = ""
        Private SerialNumberField As String = ""
        Private IssueDateField As String = ""
        Private VillageNameField As String = ""
        Private VOrgNameField As String = ""
        Private VolunteerNameField As String = ""
        Private GenderField As String = ""
        Private IdentificationIDField As String = ""
        Private BirthdayField As String = ""
        Private tgbStartDateField As String = ""
        Private tgbOrgNameField As String = ""
        Private tgsStartDateField As String = ""
        Private tgsOrgNameField As String = ""
        Private AddressField As String = ""
        Private OfficePhoneField As String = ""
        Private Active1Field As String = ""
        Private Active2Field As String = ""
        Private CommentField As String = ""

        Public Property StatePaperID() As String
            Get
                Return Me.StatePaperIDField
            End Get
            Set(ByVal value As String)
                Me.StatePaperIDField = value
            End Set
        End Property

        Public Property NO() As String
            Get
                Return Me.NOField
            End Get
            Set(ByVal value As String)
                Me.NOField = value
            End Set
        End Property

        Public Property SerialNumber() As String
            Get
                Return Me.SerialNumberField
            End Get
            Set(ByVal value As String)
                Me.SerialNumberField = value
            End Set
        End Property

        Public Property IssueDate() As String
            Get
                Return Me.IssueDateField
            End Get
            Set(ByVal value As String)
                Me.IssueDateField = value
            End Set
        End Property

        Public Property VillageName() As String
            Get
                Return Me.VillageNameField
            End Get
            Set(ByVal value As String)
                Me.VillageNameField = value
            End Set
        End Property

        Public Property VOrgName() As String
            Get
                Return Me.VOrgNameField
            End Get
            Set(ByVal value As String)
                Me.VOrgNameField = value
            End Set
        End Property

        Public Property VolunteerName() As String
            Get
                Return Me.VolunteerNameField
            End Get
            Set(ByVal value As String)
                Me.VolunteerNameField = value
            End Set
        End Property

        Public Property Gender() As String
            Get
                Return Me.GenderField
            End Get
            Set(ByVal value As String)
                Me.GenderField = value
            End Set
        End Property

        Public Property IdentificationID() As String
            Get
                Return Me.IdentificationIDField
            End Get
            Set(ByVal value As String)
                Me.IdentificationIDField = value
            End Set
        End Property

        Public Property Birthday() As String
            Get
                Return Me.BirthdayField
            End Get
            Set(ByVal value As String)
                Me.BirthdayField = value
            End Set
        End Property

        Public Property tgbStartDate() As String
            Get
                Return Me.tgbStartDateField
            End Get
            Set(ByVal value As String)
                Me.tgbStartDateField = value
            End Set
        End Property

        Public Property tgbOrgName() As String
            Get
                Return Me.tgbOrgNameField
            End Get
            Set(ByVal value As String)
                Me.tgbOrgNameField = value
            End Set
        End Property

        Public Property tgsStartDate() As String
            Get
                Return Me.tgsStartDateField
            End Get
            Set(ByVal value As String)
                Me.tgsStartDateField = value
            End Set
        End Property

        Public Property tgsOrgName() As String
            Get
                Return Me.tgsOrgNameField
            End Get
            Set(ByVal value As String)
                Me.tgsOrgNameField = value
            End Set
        End Property

        Public Property Address() As String
            Get
                Return Me.AddressField
            End Get
            Set(ByVal value As String)
                Me.AddressField = value
            End Set
        End Property

        Public Property OfficePhone() As String
            Get
                Return Me.OfficePhoneField
            End Get
            Set(ByVal value As String)
                Me.OfficePhoneField = value
            End Set
        End Property

        Public Property Active1() As String
            Get
                Return Me.Active1Field
            End Get
            Set(ByVal value As String)
                Me.Active1Field = value
            End Set
        End Property

        Public Property Active2() As String
            Get
                Return Me.Active2Field
            End Get
            Set(ByVal value As String)
                Me.Active2Field = value
            End Set
        End Property

        Public Property Comment() As String
            Get
                Return Me.CommentField
            End Get
            Set(ByVal value As String)
                Me.CommentField = value
            End Set
        End Property

    End Class

    Private Function GetWhereSQL() As String
        Return Me.GetWhereSQL(Me.chkPrintVCard.Checked)
    End Function

    Private Function GetWhereSQL(ByVal rePrint As Boolean) As String
        Dim sql As New MyStringBuilder

        'If Me.VolunteerQueryControl1.VolunteerId.Trim() = "" Then
        'If Me.VolunteerQueryControl1.Region <> "" Then
        '    sql.AppendFormat(" and (Left(v.VillageID,3) like '%{0}%' or ''='{0}')", Me.VolunteerQueryControl1.Region)
        'End If

        'If Me.VolunteerQueryControl1.Region2 <> "" Then
        '    sql.AppendFormat(" and (v.VillageID='{0}' or ''='{0}')", Me.VolunteerQueryControl1.Region2)

        'End If
        If Me.VolunteerQueryControl1.VolunteerName.Trim() <> "" Then
            sql.AppendFormat(" and v.VolunteerName like '%{0}%' ", Me.VolunteerQueryControl1.VolunteerName.Trim())
        End If

        If Me.VolunteerQueryControl1.VOrganizationID <> "0" Then
            sql.AppendFormat("AND oo.VOrganizationID = {0}  ", Me.VolunteerQueryControl1.VOrganizationID)
        End If
        If Me.VolunteerQueryControl1.OrganizationID <> "0" Then
            sql.AppendFormat("AND oo.DirectUOrganizationID = '{0}'  ", Me.VolunteerQueryControl1.OrganizationID)
        End If
        'sql.AppendFormat(" and (vb.VBookID like '%{0}%' or ''='{0}')", Me.txtVBookID.Text.Trim())

        '發證日期
        'Dim clsDate As New clsDate()
        'If clsDate.CheckDate(Me.txtIssueStartDate.Text.Trim()) And clsDate.CheckDate(Me.txtIssueEndDate.Text.Trim()) Then

        sql.AppendFormat(" and vb.IssueDate between '{0:yyyy/MM/dd}' ", Me.txtIssueStartDate.Value)
        sql.AppendFormat(" and '{0:yyyy/MM/dd}' ", Me.txtIssueEndDate.Value)

        'End If

        '紀錄冊號碼
        If Me.txtVBookID.Text <> "" Then
            sql.AppendFormat(" and SerialNumber between '{0}' and '{1}' ", Me.txtVBookID.Text.Replace("'", "''").Trim(), Me.txtVBookID2.Text.Replace("'", "''").Trim())
        End If

        '重印
        '    If rePrint = True Then
        '        sql.AppendFormat(" and Printed = 'Y' ")
        '    Else
        '        sql.AppendFormat(" and Printed = 'N' ")
        '    End If
        'Else
        If Me.VolunteerQueryControl1.VolunteerId <> "" Then
            sql.AppendFormat(" and v.VolunteerID='{0}' ", Me.VolunteerQueryControl1.VolunteerId.Trim())
        End If
        ' End If

        Return sql.ToString()
    End Function

    Private Function GetDate(ByVal oldName As String, ByVal newName As String) As String
        Dim sql As New MyStringBuilder

        sql.AppendFormat(",Case " + oldName + " when null then null ")
        sql.AppendFormat(" else Cast((Year(" + oldName + ")-1911) as varchar)+'.' ")
        sql.AppendFormat(" +Right('0'+Cast(month(" + oldName + ") as varchar),2)+'.' ")
        sql.AppendFormat(" +Right('0'+Cast(day(" + oldName + ") as varchar),2) end " + newName + " ")

        Return sql.ToString()
    End Function

    Private Sub PrintVCard()
        'Prepare Data
        Dim vcList As New List(Of VolunteerCard)
        Dim vc As VolunteerCard

        Dim vcItemList As New List(Of VolunteerCardItem)
        Dim vcItem As VolunteerCardItem

        vc = New VolunteerCard
        vc.Name = "張先生"
        'vc.VillageName = "板橋市"
        vc.OrganizationName = "台灣環保協會志工隊"
        vc.VBookID = "環保北縣字第008347號"
        vc.IssueDateString = "98 年 04 月 01 日"
        vcList.Add(vc)

        vc = New VolunteerCard
        vc.Name = "黃先生"
        '  vc.VillageName = "板橋市"
        vc.OrganizationName = "台灣環保協會志工隊"
        vc.VBookID = "環保北縣字第008347號"
        vc.IssueDateString = "98 年 04 月 01 日"
        vcList.Add(vc)

        vc = New VolunteerCard
        vc.Name = "A先生"
        ' vc.VillageName = "板橋市"
        vc.OrganizationName = "板橋志工隊"
        vc.VBookID = "環保北縣字第008347號"
        vc.IssueDateString = "98 年 04 月 01 日"
        vcList.Add(vc)

        vcList.Clear()

        Dim dt As Data.DataTable

        Using scope As New Transactions.TransactionScope
            Dim tempTable As String = "#PrintVCard"

            dt = Me.BindGVData(tempTable, Me.chkPrintVCard.Checked)

            Dim sql As New MyStringBuilder
            Dim dat As New clsData

            sql.Length = 0
            sql.AppendFormat("update v ")
            sql.AppendFormat("set Printed = 'Y' ")
            sql.AppendFormat("from VBook v ")
            sql.AppendFormat("inner join {0} t on v.CountyID = t.CountyID and v.SerialNumber = t.SerialNumber ", tempTable)

            dat.AccData(sql)

            scope.Complete()
        End Using

        Dim i As Integer = 1
        For Each dr As Data.DataRow In dt.Rows
            vc = New VolunteerCard
            vc.Name = dr("VolunteerName").ToString()
            vc.OrganizationName = dr("VOrganizationName").ToString()
            ' vc.TownName = dr("TownName").ToString()
            vc.VBookID = dr("VBookID").ToString()
            vc.Index = i

            If Not TypeOf dr("PhotoPath") Is DBNull Then
                vc.Photo = Me.GetPhoto2(dr("PhotoPath").ToString())
            End If

            If TypeOf dr("IssueDate") Is DBNull Then
                'vc.IssueDateString = "98 年 04 月 01 日"
                vc.IssueDateString = "   年    月    日"
            Else
                vc.IssueDateString = String.Format("{0} 年 {1:MM 月 dd 日} ", CType(dr("IssueDate"), DateTime).Year - 1911, CType(dr("IssueDate"), DateTime))
            End If

            vcList.Add(vc)

            vcItem = New VolunteerCardItem
            Dim MyRandom As New clsRandom
            vcItem.Index = i
            vcItem.Randomld = Right("0000000" & i, 8) '動態的ID編號
            vcItemList.Add(vcItem)

            i = i + 1
        Next

        'Print

        Dim fileName As String = "VCard.doc"
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName)

        Dim velocity As New VelocityEngine
        Dim props As New Commons.Collections.ExtendedProperties

        'fix bug
        props.AddProperty("file.resource.loader.path", Server.MapPath("~\App_Data"))
        props.AddProperty("input.encoding", "utf-8")
        props.AddProperty("output.encoding", "utf-8")
        velocity.Init(props)

        Dim template As Template = velocity.GetTemplate("志工證.xml")

        Dim context As New VelocityContext
        context.Put("vc2", vc)
        context.Put("VolunteerCardList", vcList)
        context.Put("VolunteerCardItemList", vcItemList)
        context.Put("User", clsAuth.GetUserID())
        context.Put("DownloadDate", Today.Year.ToString() & "-" & Today.Month.ToString() & "-" & Today.Day.ToString() & "T" & Now.Hour.ToString() & ":" & Now.Minute.ToString() & ":" & Now.Second.ToString() & "Z")
        context.Put("IP", MyObj.getIP())
        Dim writer As New IO.StringWriter
        template.Merge(context, writer)

        Response.Write(writer.GetStringBuilder().ToString())

        'Response.WriteFile(Server.MapPath("~\App_Data\志工證.xml"))
        Response.End()

    End Sub
    Private Sub PrintVolunteerBook(ByVal reprint As Boolean)
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        Dim dt As Data.DataTable
        sql.Length = 0

        sql.AppendFormat(" select distinct v.PhotoPath,v.VolunteerName,vb.VBookID  ")
        sql.AppendFormat(",oo.VOrganizationName ")
        sql.AppendFormat(",ov.OrganizationName ")
        sql.AppendFormat("from VolunteerDistinctView v ")
        sql.AppendFormat("  left JOIN (select vm.VOrganizationID,vo.VOrganizationName,vm.VolunteerID ,vo.DirectUOrganizationID from VOrganizationMapping vm ")
        sql.AppendFormat("inner join VOrganizationViewV2 vo on vm.VOrganizationID=vo.VOrganizationID ) oo on v.VolunteerID=oo.VolunteerID  ")
        sql.AppendFormat("left join OrganizationView ov on oo.DirectUOrganizationID=ov.UOrganizationID ")

        'sql.AppendFormat("inner join VolunteerView vi on vv.UOrganizationID = vi.UOrganizationID ")
        sql.AppendFormat("inner join VBookView vb on v.VolunteerID = vb.VolunteerID ")
        'sql.AppendFormat("inner join Village r on v.VillageID = r.RegionID ")
        sql.AppendFormat("where vb.Active = 'Y' ")
        sql.AppendFormat("and vb.VBookID like '%環%' ")
        sql.AppendFormat(GetWhereSQL(reprint))
        If Me.gv.OrderBySQL <> "" Then
            sql.AppendFormat(Me.gv.OrderBySQL)
        End If
        'MyObj.WriteLog(sql.ToString())
        dt = dat.GetData(sql)


        Dim VbList As New List(Of VolunteerBook)
        Dim vb As VolunteerBook
        Dim dr As Data.DataRow
        For i As Integer = 0 To dt.Rows.Count - 1
       
            dr = dt.Rows(i)

            vb = New VolunteerBook
            vb.Index1 = i
       

            If Not TypeOf dr("OrganizationName") Is DBNull Then
                vb.OrgName1 = dr("OrganizationName").ToString()
            Else
                vb.OrgName1 = ""
            End If

            If Not TypeOf dr("PhotoPath") Is DBNull Then
                vb.PhotoPath1 = Me.GetPhoto2(dr("PhotoPath").ToString())
            Else
                vb.PhotoPath1 = ""
            End If

            If Not TypeOf dr("VolunteerName") Is DBNull Then
                vb.VolunteerName1 = dr("VolunteerName").ToString()
            Else
                vb.VolunteerName1 = ""
            End If

            i = i + 1
            If i <= dt.Rows.Count - 1 Then
                dr = dt.Rows(i)
                vb.Index2 = i
             

                If Not TypeOf dr("OrganizationName") Is DBNull Then
                    vb.OrgName2 = dr("OrganizationName").ToString()
                Else
                    vb.OrgName2 = ""
                End If

                If Not TypeOf dr("PhotoPath") Is DBNull Then
                    vb.PhotoPath2 = Me.GetPhoto2(dr("PhotoPath").ToString())
                Else
                    vb.PhotoPath2 = ""
                End If


                If Not TypeOf dr("VolunteerName") Is DBNull Then
                    vb.VolunteerName2 = dr("VolunteerName").ToString()
                Else
                    vb.VolunteerName2 = ""
                End If
            Else
                vb.OrgName2 = ""
                vb.PhotoPath2 = ""
                vb.VolunteerName2 = ""
            End If

            VbList.Add(vb)
        Next

        'Print

        Dim fileName As String = "VNameList.doc"
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName)

        Dim velocity As New VelocityEngine
        Dim props As New Commons.Collections.ExtendedProperties

        'fix bug
        props.AddProperty("file.resource.loader.path", Server.MapPath("~\App_Data"))
        props.AddProperty("input.encoding", "utf-8")
        props.AddProperty("output.encoding", "utf-8")
        velocity.Init(props)

        Dim template As Template = velocity.GetTemplate("紀錄冊名條.xml")

        Dim context As New VelocityContext
        context.Put("VBook", VbList)
        context.Put("User", clsAuth.GetUserID())
        context.Put("DownloadDate", Today.Year.ToString() & "-" & Today.Month.ToString() & "-" & Today.Day.ToString() & "T" & Now.Hour.ToString() & ":" & Now.Minute.ToString() & ":" & Now.Second.ToString() & "Z")
        context.Put("IP", MyObj.getIP())


        Dim writer As New IO.StringWriter
        template.Merge(context, writer)

        Response.Write(writer.GetStringBuilder().ToString())

        Response.End()
    End Sub
    Public Class VolunteerBook

        Private OrgName1Field As String
        Private PhotoPath1Field As String
        Private VolunteerName1Field As String
        Private Index1Field As Integer
        Private OrgName2Field As String
        Private Index2Field As Integer
        Private PhotoPath2Field As String
        Private VolunteerName2Field As String
        Public Property OrgName1() As String
            Get
                Return Me.OrgName1Field
            End Get
            Set(ByVal value As String)
                Me.OrgName1Field = value
            End Set
        End Property
        Public Property PhotoPath1() As String
            Get
                Return Me.PhotoPath1Field
            End Get
            Set(ByVal value As String)
                Me.PhotoPath1Field = value
            End Set
        End Property
        Public Property VolunteerName1() As String
            Get
                Return Me.VolunteerName1Field
            End Get
            Set(ByVal value As String)
                Me.VolunteerName1Field = value
            End Set
        End Property
        Public Property OrgName2() As String
            Get
                Return Me.OrgName2Field
            End Get
            Set(ByVal value As String)
                Me.OrgName2Field = value
            End Set
        End Property
        Public Property PhotoPath2() As String
            Get
                Return Me.PhotoPath2Field
            End Get
            Set(ByVal value As String)
                Me.PhotoPath2Field = value
            End Set
        End Property
        Public Property VolunteerName2() As String
            Get
                Return Me.VolunteerName2Field
            End Get
            Set(ByVal value As String)
                Me.VolunteerName2Field = value
            End Set
        End Property
        Public Property Index1() As Integer
            Get
                Return Me.Index1Field
            End Get
            Set(ByVal value As Integer)
                Me.Index1Field = value
            End Set
        End Property
        Public Property Index2() As Integer
            Get
                Return Me.Index2Field
            End Get
            Set(ByVal value As Integer)
                Me.Index2Field = value
            End Set
        End Property
    End Class
    Public Class VolunteerCard
        Private NameField As String
        Private OrganizationNameField As String
        'Private TownNameField As String
        Private VBookIDField As String
        Private IssueDateStringField As String
        Private IndexField As Integer
        Private PhotoField As String

        Public Property Name() As String
            Get
                Return Me.NameField
            End Get
            Set(ByVal value As String)
                Me.NameField = value
            End Set
        End Property

        Public Property OrganizationName() As String
            Get
                Return Me.OrganizationNameField
            End Get
            Set(ByVal value As String)
                Me.OrganizationNameField = value
            End Set
        End Property

        'Public Property TownName() As String
        '    Get
        '        Return Me.TownNameField
        '    End Get
        '    Set(ByVal value As String)
        '        Me.TownNameField = value
        '    End Set
        'End Property

        Public Property VBookID() As String
            Get
                Return Me.VBookIDField
            End Get
            Set(ByVal value As String)
                Me.VBookIDField = value
            End Set
        End Property

        Public Property IssueDateString() As String
            Get
                Return Me.IssueDateStringField
            End Get
            Set(ByVal value As String)
                Me.IssueDateStringField = value
            End Set
        End Property

        Public Property Index() As Integer
            Get
                Return Me.IndexField
            End Get
            Set(ByVal value As Integer)
                Me.IndexField = value
            End Set
        End Property

        Public Property Photo() As String
            Get
                Return Me.PhotoField
            End Get
            Set(ByVal value As String)
                Me.PhotoField = value
            End Set
        End Property
    End Class

    Public Class VolunteerCardItem
        Private IndexField As Integer
        Private RandomldField As String

        Public Property Index() As String
            Get
                Return Me.IndexField
            End Get
            Set(ByVal value As String)
                Me.IndexField = value
            End Set
        End Property

        Public Property Randomld() As String
            Get
                Return Me.RandomldField
            End Get
            Set(ByVal value As String)
                Me.RandomldField = value
            End Set
        End Property
    End Class

    Private ReadOnly Property photoBasePath() As String
        Get
            If ViewState("photoBasePath") Is Nothing Then
                ViewState("photoBasePath") = MyObj.GetFilePath("VBookPhoto")
            End If

            Return ViewState("photoBasePath")
        End Get
    End Property


    Private Function GetPhoto(ByVal photoFileName As String) As String
        'Dim photoPath As String = Me.photoBasePath + "\" + Integer.Parse(vbookID).ToString() + ".png"
        Dim photoPath As String = Server.MapPath(Me.photoBasePath + photoFileName)

        'Dim photo As System.Drawing.Image = System.Drawing.Image.FromFile("a")
        'MyObj.WriteLog(photoPath)

        'Dim s As BinaryReader

        If File.Exists(photoPath) Then
            Try
                Using s = New BinaryReader(New FileStream(photoPath, FileMode.Open))
                    Dim b() As Byte = s.ReadBytes(s.BaseStream.Length)

                    Dim ss As String = Convert.ToBase64String(b)

                    Return ss
                End Using
            Catch ex As System.Exception
                MyObj.WriteErrorLog(ex.Message)
                Return ""
                'Finally
                '    If s IsNot Nothing Then
                '        s.Close()
                '    End If
            End Try
        Else
            Return ""
        End If

    End Function

    Private Function GetPhoto2(ByVal photoFileName As String) As String
        Dim photoPath As String = Server.MapPath(Me.photoBasePath + photoFileName)
        Dim ReturnValue As String = ""
        Try
            If File.Exists(photoPath) Then
                Dim data As String = Nothing
                Dim img As System.Drawing.Image
                img = System.Drawing.Image.FromFile(photoPath)

                Try
                    Dim MyRandom As New clsRandom
                    Dim MyPath As String = Server.MapPath(Me.photoBasePath + MyRandom.Generate(8) & ".jpg")
                    img.Save(MyPath, System.Drawing.Imaging.ImageFormat.Jpeg)
                    img.Dispose()

                    Using s = New BinaryReader(New FileStream(MyPath, FileMode.Open))
                        Dim b() As Byte = s.ReadBytes(s.BaseStream.Length)

                        Dim ss As String = Convert.ToBase64String(b)


                        ReturnValue = ss
                    End Using

                    File.Delete(MyPath)
                    Return ReturnValue
                Catch ex As System.Exception
                    MyObj.WriteErrorLog(ex.Message)
                    Return ""
                End Try
            Else
                Return ""
            End If
        Catch ex As System.Exception
            MyObj.WriteErrorLog(ex.Message)
            Return ""
        End Try
    End Function

    Private ReadOnly Property VolunteerID() As String
        Get
            Return Me.VolunteerQueryControl1.VolunteerId
        End Get
    End Property

    Private ReadOnly Property VolunteerName() As String
        Get
            Return Me.VolunteerQueryControl1.VolunteerName
        End Get
    End Property

    'Private ReadOnly Property IsOrganization() As Boolean
    '    Get
    '        If Me.ddlOrganizationID.SelectedValue.Split(",")(0) = "-1" Then
    '            Return False
    '        Else
    '            Return True
    '        End If
    '    End Get
    'End Property

    'Private ReadOnly Property OrganizationRoot() As String
    '    Get
    '        Return Me.ddlOrganizationID.SelectedValue.Split(",")(0)
    '    End Get
    'End Property

    'Private ReadOnly Property VOrganizationRoot() As String
    '    Get
    '        Return Me.ddlOrganizationID.SelectedValue.Split(",")(1)
    '    End Get
    'End Property

    Public Property CurrentRowIndex() As String
        Get
            Return ViewState("CurrentRowIndex")
        End Get
        Set(ByVal value As String)
            ViewState("CurrentRowIndex") = value
        End Set
    End Property

    Public ReadOnly Property DataKey() As String
        Get
            Return Me.gv.DataKeys(Me.CurrentRowIndex)("ID")
        End Get
    End Property

    Public ReadOnly Property SelectedVolunteerID() As String
        Get
            If Me.gv.SelectedRow Is Nothing Then
                Return Me.gv.Rows(0).Cells(1).Text
            Else
                Return Me.gv.SelectedRow.Cells(1).Text
            End If
        End Get
    End Property
    Public Property IsVisible() As Boolean
        Get
            If ViewState("IsVisible") Is Nothing Then
                ViewState("IsVisible") = True
            End If
            Return ViewState("IsVisible")
        End Get
        Set(ByVal value As Boolean)
            ViewState("IsVisible") = value
        End Set
    End Property

    Public Event Loaded(ByVal source As Object, ByVal e As EventArgs)
    Public Event SelectedIndexChanged(ByVal source As Object, ByVal e As EventArgs)
    Public Event Viewing(ByVal source As Object, ByVal e As EventArgs)
    Public Event btnQueryClick(ByVal sender As Object, ByVal e As System.EventArgs)
End Class